package cn.tedu.csmall.commons.ex.handler;


import cn.tedu.csmall.commons.ex.ServiceException;
import cn.tedu.csmall.commons.web.ServiceCode;
import cn.tedu.csmall.commons.web.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;


/**
 * 全局异常处理器
 *
 * @author java@tedu.cn
 * @version 0.0.1
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler
    public JsonResult handlerServiceException(ServiceException e){
        log.warn("程序运行过程中出现了ServiceException,将统一处理！");
        log.warn("异常信息：{}",e.getMessage());
        return JsonResult.fail(e.getServiceCode(), e.getMessage());
    }

    @ExceptionHandler
    public JsonResult handleBindException(BindException e) {
        log.warn("程序运行过程中出现了BindException,将统一处理！");
        log.warn("异常信息：{}",e.getMessage());

        String message = e.getFieldError().getDefaultMessage();

        return JsonResult.fail(ServiceCode.ERR_BAD_REQUEST,message);



    }


    @ExceptionHandler
    public JsonResult handleConstraintViolationException(ConstraintViolationException e){
        log.warn("程序运行过程中出现了ConstraintViolationException,将统一处理！");
        log.warn("异常信息：{}",e.getMessage());
        String message = null;
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        for (ConstraintViolation<?> constraintViolation : constraintViolations) {
            message = constraintViolation.getMessage();
        }
//        JsonResult jsonResult = new JsonResult();
//        jsonResult.setState(3);
//        jsonResult.setMessage(message);
        return JsonResult.fail(ServiceCode.ERR_BAD_REQUEST,message);
    }





//【注意】在项目正式上线时，禁止使用 e.printStackTrace();
    @ExceptionHandler
    public JsonResult handleThrowable(Throwable e){
        log.warn("程序运行过程中出现了Throwable,将统一处理！");
        log.warn("异常：",e); //取代e.printStackTrace();
        String message = "服务器忙，请稍后再试！ 【在开发过程中，如果看到此提示，应该检查服务器端的控制台，分析异常，并在全局异常处理器中补充处理对应异常的方法】";


//        JsonResult jsonResult = new JsonResult();
//        jsonResult.setState(99999);
//        jsonResult.setMessage(message);
        return JsonResult.fail(ServiceCode.ERR_UNKNOWN,message);
    }
}
